<?php
namespace Manage\Controller;
use Think\Controller;


class CommonController extends Controller {
    
    public function _initialize(){
        
        
        $this->assign("menu",  $this->getMenu());
        

    }
    
    
    private function getMenu() {
        $where["pid"] = 0;
        $menu["main"] = M("menu")->where($where)->order("sort")->select();
        $menu['child'] = array();

        $selected = M("menu")->where("url like '%" . CONTROLLER_NAME . "/" . ACTION_NAME . "%' and pid != 0")->field('id,pid')->find();
        
        $where['pid'] = $selected['pid'];


        foreach ($menu['main'] as $key => $value) {
            if ($value['id'] === $selected['pid']) {
                $menu['main'][$key]['class'] = "selected";
            }
        }
        
        $nav = M('Menu')->where($where)->select();
        
        if ($nav) {
            $groups = array_filter(array_unique(array_column($nav, 'group')));
        } else {
            $groups = array();
        }
        $child = array();
        for($i=0;$i<count($nav);$i++){
            if($nav[$i]["group"] !== null){
                $groupTitle = $nav[$i]["group"];
                $child[$groupTitle]['title'] = $groupTitle;
                if(!is_array($child[$groupTitle]['child'])){
                    $child[$groupTitle]['child'] = array();
                }
                array_push($child[$groupTitle]['child'], $nav[$i]);
                
            }else{
                array_push($child, $nav[$i]);
            }
            
        }
        $menu['child'] = $child;
        return $menu;
    }

//    public function getChild($pid){
//        $b = M("menu")->where("pid = $pid")->select();
//        for ($i = 0; $i < count($b); $i++) {
//
//            echo $i . "=" . $b[$i]['id'] . "<br>";
//            $d = $this->getChild($b[$i]['id']);
//            $b[$i]['child'] = $d;
//        }
//        return $b;
//    }
    
    
    
    
//    public function getMenu123($pid=0) {
//        
//        $menu1 = M("menu")->where(array('pid'=>$pid))->select();
//        for($i=0;$i<count($menu1);$i++){
//            $temp_menus[$menu1[$i]['title']] = $this->getMenu123($menu1[$i]['id']);
//        }
//        return $temp_menus;
//        
//    }
    
}